<?php
namespace App\Http\Controllers\Api\Repositories;

use App\Models\Posts\WxLike as Model;
use App\Models\Posts\WxPost;
use App\Models\WxNotice;
use App\Models\User\WxUser;
use App\Wen\Utils\FieldUtils;
use App\Wen\Utils\UserUtils;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class WxLikeRepositores
{
    /**
     * Model.
     *
     * @var string
     */
    protected $eloquentClass = Model::class;

    /**
     * 点赞
     */
    public static function admin_like($uid, $posts_id)
    {
        DB::beginTransaction();
        try {

            $posts_user_id = WxPost::where('id', $posts_id)->value('user_id');

            if(_empty_($posts_user_id)){
                DB::rollBack();
                return false;
            }

            $isExists = Model::where('posts_id', $posts_id)
                ->where('user_id', $uid)
                ->exists();
            if (!$isExists) {
                // 点赞
                $wxLike = new Model();
                $wxLike->posts_user_id = $posts_user_id;
                $wxLike->posts_id = $posts_id;
                $wxLike->user_id = $uid;
                $wxLike->created_at = time();
                $wxLike->updated_at = time();
                $wxLike->save();

                $user = UserUtils::get_cached_user($uid);

                if($posts_user_id != $user['id']) {
                    UserUtils::add_user_notice(2003, $posts_user_id, '收到了一个喜欢', '您的笔记收到了「' . '<a href="/pages/user/user?id=' . $user['id'] . '">' . $user['user_name'] . '</a>' . '」的喜欢。', 101, $posts_id);
                }
            }
            Redis::sadd('realtime:post:set', $posts_id);
            Cache::forget('posts:likeCont:'.$posts_id);
            DB::commit();

            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            _logger_(__file__, __line__, $e->getMessage());
            return false;
        }

    }

    public static function unlike($uid, $posts_id)
    {
        DB::beginTransaction();
        try {
            $posts_user_id = WxPost::where('id', $posts_id)->pluck('user_id')->first();
            // 取消点赞
            (new Model())->where('posts_id', $posts_id)
                ->where('user_id', $uid)
                ->delete();

            (new WxNotice())->where('posts_id', $posts_id)
                ->where('user_id', $posts_user_id)
                ->where('notice_type', 2)
                ->delete();
            Redis::sadd('realtime:post:set', $posts_id);
            DB::commit();
            return true;

        } catch (\Exception $e) {
            DB::rollBack();
            _logger_(__file__, __line__, $e->getMessage());
            return false;
        }
    }

}
